from utils.stream.filestream import FileStream
from utils.stream.valve import Valve
from utils.stream.stream import Stream
from defs.exception import BlaIOError
from random import randint
import unittest
import os
from time import time

class TestValve(unittest.TestCase):
    def setUp(self):
        self.testfile = FileStream("testfile")
        self.testfile.open()
        #for x in range(1024 * 1024):
          #  self.testfile.write(chr(randint(0, 255)))
        
        #[self.testfile.write(chr(randint(0, 255))) for x in range(1024**2)]
        
        # faster one
        #for y in [x%10 for x in range(1024*1024)]:
        #    self.testfile.write(str(y))
        for y in [randint(1, 254) for x in range(1024*1024)]:
            self.testfile.write(chr(y))
        
        #self.testfile.seek(0, os.SEEK_SET)
  
        """
        pos = 0
        while True:
            x = self.testfile.read(1)
            if not x: break
            self.assertEqual(str(pos%10), x)
            pos += 1
        self.testfile.seek(0, os.SEEK_SET)
        """
        
        
    def tearDown(self):
        self.testfile.close()
        os.remove("testfile")
        
        
    def testValve(self):
        
        
        destfile = FileStream("testcopy1", writeonly = True)
        destfile.open()
        self.testfile.seek(0)
        #pos = 0
        timestart = time()
        while True:
            x = self.testfile.read(1024*64)
            #print x
            if not x: break
            """
            for y in range(len(x)):
                self.assertEqual(x[y], str((pos + y)%10))
            pos += 64
            """
            destfile.write(x)
        timeend = time()
        destfile.close()
        os.remove("testcopy1")
        time1 = timeend - timestart
        
        destfile = FileStream("testcopy2", writeonly = True)
        destfile.open()
        self.testfile.seek(0)
        valve = Valve(64*1024)
        valve.open()
        valve.addOutBranch(destfile)
        timestart = time()
        while True:
            x = self.testfile.read(1024 * 1024)
            if not x: break
            valve.write(x)
        timeend = time()
        destfile.close()
        valve.close()
        os.remove("testcopy2")
        time2 = timeend - timestart
        
        #print "time1 is", time1
        #print "time2 is", time2
        self.assertTrue(time1 < time2)
        
        
        
suite = unittest.TestLoader().loadTestsFromTestCase(TestValve)
if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=2).run(suite)
